<?php

namespace app\common\service;

use ba\Random;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Tts\V20190823\Models\CreateTtsTaskRequest;
use TencentCloud\Tts\V20190823\Models\DescribeTtsTaskStatusRequest;
use TencentCloud\Tts\V20190823\Models\TextToVoiceRequest;
use TencentCloud\Tts\V20190823\TtsClient;
use think\exception\ValidateException;
use think\facade\Log;
use function Symfony\Component\Translation\t;

class TencentVocalService extends ApiService
{

    private $secretId;
    private $secretKey;
    private $region;

    private TtsClient $client;


    public function __construct()
    {
        $this->secretId = env('TENCENT.TENCENTCLOUD_SECRET_ID', '');
        $this->secretKey = env('TENCENT.TENCENTCLOUD_SECRET_KEY', '');
        $this->region = 'ap-hongkong'; // 设置合适的区域
        $this->setClient();
    }

    public function setClient()
    {
        $cred = new Credential($this->secretId, $this->secretKey);
        $this->client = new TtsClient($cred, $this->region);
        return true;
    }

    public function textToVoiceByte(string $word, int|float $speed = null)
    {
        try {
            $req = new TextToVoiceRequest();
            $req->setText($word);
            $req->setSessionId(Random::uuid());
            $req->setSpeed($speed ?? 0);
            $req->setPrimaryLanguage(2);
            $req->setCodec('mp3');
            $resp = $this->client->TextToVoice($req);
            $audio = $resp->getAudio();
            $res = base64_decode($audio);
        } catch (TencentCloudSDKException|ValidateException $e) {
            $this->setError('语音合成生成失败');
            return false;
        }
        return $res;
    }

    public function longTextToVoiceTheStandardAndEn(string $text, string $callbackUrl)
    {
        try {
            $req = new CreateTtsTaskRequest();
            $req->setText($text);
            $req->setVoiceType(1051);
            $req->setCallbackUrl(request()->domain() . $callbackUrl);
            $resp = $this->client->createTtsTask($req);
            logSave($resp,'longTextToVoiceTheStandardAndEn');
            $taskId = $resp->getData()->getTaskId();
        } catch (TencentCloudSDKException|ValidateException $e) {
            $this->setError('语音合成生成失败');
            return false;
        }
        return $taskId;
    }

    public function longTextToVoiceCallback($callback)
    {
        if (!isset($callback['Status']) || $callback['Status'] != 2) {
            $callback = json_encode($callback);
            $this->setError("腾讯TTL 长语音回调{$callback}");
            return false;
        }
        $resultUrl = $callback['ResultUrl'];

        $uploadService = new UploadService();
        $saveName = $uploadService->generateUniqueFileName('mp3');
        return $uploadService->copyObject($resultUrl, $saveName);
    }

    public function longTextToSpeechResultQuery($taskId)
    {
        try {
            $request = new DescribeTtsTaskStatusRequest();
            $request->setTaskId($taskId);
            $response = $this->client->DescribeTtsTaskStatus($request);
            return $response->getData();
        } catch (TencentCloudSDKException|ValidateException $e) {
            $this->setError('腾讯云长语音合成结果查询 调用异常');
            return false;
        }
    }


}